import 'dart:convert';
import 'dart:ui';

import 'package:get/get.dart';
import 'package:sainbainu/common/services/storage.dart';
import 'package:sainbainu/common/values/storage_keys.dart';

class AppService extends GetxService {
  static AppService get to => Get.find();

  AppService();

  /// 是否第一次打开 app
  bool _isFirstOpenApp = true;
  bool get isFirstOpenApp => _isFirstOpenApp;

  /// 获取应用语言
  Locale? _locale;
  Locale? get locale => _locale;

  @override
  void onInit() {
    super.onInit();

    var isFirstOpenApp = StorageService.to.getBool(StorageKeys.firstOpenApp);
    _isFirstOpenApp = isFirstOpenApp ?? true;

    var localeString = StorageService.to.getString(StorageKeys.appLocale);
    if (localeString != null && localeString.isNotEmpty) {
      Map localeMap = json.decode(localeString);
      _locale = Locale(localeMap['languageCode'], localeMap['countryCode']);
    }
  }

  /// 设置是否第一次打开 app
  void setFirstOpenApp(bool value) {
    _isFirstOpenApp = value;
    StorageService.to.setBool(StorageKeys.firstOpenApp, value);
  }

  /// 设置应用语言
  void setLocale(Locale value) {
    var localeMap = {
      'languageCode': value.languageCode,
      'countryCode': value.countryCode,
    };
    var localeString = json.encode(localeMap);
    StorageService.to.setString(StorageKeys.appLocale, localeString);
    _locale = value;
  }
}
